<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { ElTable, ElMessageBox, FormInstance, type FormRules, ElMessage } from "element-plus"
import { formatDateTime } from "@/utils"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh } from "@element-plus/icons-vue"
import { useRouter } from "vue-router"
import { useCascaderAreaData } from "@vant/area-data"
import {
  createCompilationChildApi,
  deleteCompilationChildApi,
  updateCompilationChildApi,
  getCompilationChildApi
} from "@/api/combo"
import { useComboStore } from "@/store/modules/combo"
const loading = ref(true)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "childset"
})
const areaoptions = useCascaderAreaData()
const props = {
  multiple: true,
  checkStrictly: true,
  label: "text",
  value: "text"
}
const router = useRouter()
const pid = router.currentRoute.value.query.id //套餐合集ID
const compilationId = ref<any>(undefined)
const handleUpdate = (row: any) => {
  compilationId.value = row.id
  formData.packageName = row.packageName
  formData.packageId = row.packageId
  formData.type = row.type
  formData.grade = row.grade
  formData.province = eval(row.province)
  formData.packageArea = eval(row.packageArea)
  dialogVisible.value = true
}
// #region  删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`您确定要删除:${row.packageName}吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCompilationChildApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getApplet()
    })
  })
}
// #endregion

// #region 增
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  packageName: "",
  packageId: "",
  type: 0,
  province: "",
  grade: "",
  packageArea: ""
})
const dialogVisible = ref<boolean>(false)
const rules: FormRules = reactive({
  packageId: [{ required: true, trigger: "blur", message: "请输选择套餐" }],
  type: [{ required: true, trigger: "blur", message: "请输选择套餐类型" }],
  province: [{ required: true, trigger: "blur", message: "请输选择发货地" }],
  grade: [{ required: true, trigger: "blur", message: "请填写级别" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (compilationId.value === undefined) {
        createCompilationChildApi({
          heId: pid,
          packageName: formData.packageName,
          packageId: formData.packageId,
          type: formData.type,
          grade: formData.grade,
          province: arrToStr(formData.province),
          packageArea: arrToStr(formData.packageArea)
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getApplet()
        })
      } else {
        updateCompilationChildApi({
          heId: pid,
          id: compilationId.value,
          packageName: formData.packageName,
          packageId: formData.packageId,
          type: formData.type,
          grade: formData.grade,
          province: arrToStr(formData.province),
          packageArea: arrToStr(formData.packageArea)
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getApplet()
        })
      }
    } else {
      return false
    }
  })
}

const resetForm = () => {
  compilationId.value = undefined
  clearValidate()
  formData.packageName = ""
  formData.packageId = ""
  formData.type = 0
  formData.province = ""
  formData.packageArea = ""
}
// #endregion

// #region 查
const tableTotal = ref<number>()
const tableData = ref<any>([])
const getApplet = () => {
  getCompilationChildApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    id: pid
  })
    .then((res: any) => {
      tableData.value = res.data.list
      tableTotal.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  packageName: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getApplet()
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getApplet()
  }
  paginationData.currentPage = 1
}
const arrToStr = (objarr: any) => {
  const arrLen = objarr.length
  let row = "["
  for (let i = 0; i < arrLen; i++) {
    row += "["
    for (let j = 0; j < objarr[i].length; j++) {
      row += `'${objarr[i][j]}'`
      if (j < objarr[i].length - 1) {
        row += ","
      }
    }
    row += "]"
    if (i < arrLen - 1) {
      row += ","
    }
  }
  row += "]"
  return row
}
// #endregion
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getApplet, { immediate: true })
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const comboStore = useComboStore()
comboStore.getComoboFn()
const comboList1 = ref<any>([])
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    // comboList.value = newValue.flat()
    comboList1.value = newValue.flat().filter((item) => item.state === "true")
  },
  {
    immediate: true
  }
)

const comboChange = (val: any) => {
  comboList1.value.filter((item: any) => {
    if (item.id === val) {
      formData.packageName = item.name
    }
  })
}

const strTo = (val: any) => {
  return eval(val).flat().join(",")
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="套餐名称">
          <el-input v-model.trim="searchData.packageName" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 顶部添加 -->
      <div class="middle-top">
        <div>
          <el-button type="primary" @click="dialogVisible = true">添加套餐</el-button>
        </div>
        <div style="margin-top: 20px; font-size: 14px; color: red">
          级别定义:普通套餐级别默认0，保底套餐可自定义设置非0数值，订单轮转根据级别从小到大依次进行
        </div>
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-table :data="tableData">
          <el-table-column prop="create" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="packageName" label="套餐名称" align="center" />
          <el-table-column prop="type" label="套餐类型" align="center">
            <template #default="scope">
              <span v-if="scope.row.type == 1">保底套餐</span>
              <span v-else>普通套餐</span>
            </template>
          </el-table-column>
          <el-table-column prop="grade" label="级别" align="center" />
          <el-table-column prop="province" label="发货地区" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.type == 1">{{}}</span>
              <span v-else>{{ strTo(scope.row.province) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="packageArea" label="不发货地区" align="center" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.type == 1">{{ strTo(scope.row.packageArea) }}</span>
              <span v-else>{{}}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="left">
            <template #default="scope">
              <p>
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              </p>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="compilationId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="left">
        <el-form-item prop="packageId" label="套餐">
          <el-select
            v-model="formData.packageId"
            clearable
            filterable
            placeholder="请选套餐,可输入快速查询"
            style="width: 100%"
            @change="comboChange"
          >
            <!-- :value="item.id + ''" -->
            <el-option
              v-for="item in comboList1"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.state === 'false'"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="type" label="套餐类型">
          <el-select v-model="formData.type" placeholder="请选择" style="width: 100%">
            <el-option key="1" label="普通" :value="0" />
            <el-option key="2" label="保底套餐" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item prop="province" label="发货地区" v-if="formData.type != 1">
          <el-cascader
            style="width: 100%"
            size="large"
            placeholder="可输入地址快速查询"
            :props="props"
            :options="areaoptions"
            v-model="formData.province"
            :filterable="true"
          />
        </el-form-item>
        <el-form-item prop="packageArea" label="不发货地" v-if="formData.type == 1">
          <el-cascader
            style="width: 100%"
            size="large"
            placeholder="可输入地址快速查询"
            :props="props"
            :options="areaoptions"
            v-model="formData.packageArea"
            :filterable="true"
          />
        </el-form-item>
        <el-form-item prop="grade" label="级别" v-if="formData.type == 1">
          <el-input v-model="formData.grade" placeholder="请输入保底套餐的级别,用于轮转时的排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
